package com.shijie.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import com.shijie.component.ErpUserService;
import com.shijie.core.AbstractService;
import com.shijie.domain.entity.Categories;
import com.shijie.domain.entity.Coupons;
import com.shijie.domain.entity.Magazines;
import com.shijie.domain.entity.Recommends;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.mapper.RecommendsMapper;

/*
 *  @author: smart boy
 *  @date: 2018-08-23
 */
@Service
public class RecommendsService extends AbstractService<Recommends> {

	@Resource
	private RecommendsMapper recommendsMapper;
	@Resource
	private BrandsService brandsService;
    @Resource
	private ProductsService productsService;
	@Resource
	private ErpUserService erpUserService;
	@Resource
	private MagazinesService magazinesService;
	@Resource
	private CategoriesService categoriesService;
	@Resource
	private CouponsService couponsService;
	
	public void save(Recommends r){
		if(r.getId() == null){
			r.setCreateBy(erpUserService.getUserName());
			r.setCreateTime(DateTime.now().toDate());
			recommendsMapper.insert(r);
		}else{
			r.setUpdateBy(erpUserService.getUserName());
			r.setUpdateTime(DateTime.now().toDate());
			recommendsMapper.updateByPrimaryKey(r);
		}
	}
	
	public List search(String q ,Integer type) {
		if (type == 0) {
			return productsService.searchProducts(q,null,null);
		} else if(type == 1){
			return brandsService.list(q, null);
		}
		else if(type == 6){
			Condition condition = new Condition(Coupons.class);
			Example.Criteria c = condition.createCriteria().andEqualTo("brandId",0).andEqualTo("status",0);
			if(!StringUtils.isEmpty(q)){
				c.andLike("name", "%"+q+"%");	
			}
			return couponsService.selectByCondition(condition);
		}
		else{
			Condition condition = new Condition(Categories.class);
			Example.Criteria c = condition.createCriteria().andEqualTo("status",0);
			if(!StringUtils.isEmpty(q)){
				c.andLike("name", "%"+q+"%");	
			}
			return categoriesService.selectByCondition(condition);
		}
	}

	public List<Recommends> selectRecommends(Integer position) {
		Condition condition = new Condition(Recommends.class);
		Example.Criteria criteria = condition.createCriteria();
		criteria.andEqualTo("position", position);
		criteria.andEqualTo("status", EnumInterface.Status.VALID.ordinal());
		condition.orderBy("sort").asc();
		return recommendsMapper.selectByCondition(condition);
	}

}
